//
//  HPDropDownListView.m
//  V-POS
//
//  Created by handpay on 12-11-19.
//  Copyright (c) 2012年 handpay. All rights reserved.
//

#import "HPDropDownListView.h"
#import "DefineUtil.h"
#import "CategoryUtil.h"
#import "HPUIEngine.h"
//#import "HPUtility.h"

@interface HPDropDownListView ()

@property(retain, nonatomic) NSArray *dataArray;

@property(nonatomic, assign) NSInteger realNumberOfComponents;

@property(nonatomic, retain) NSString *noDataTip;

@property (retain, nonatomic) NSMutableArray *selectedIndexs;

@end

@implementation HPDropDownListView
@synthesize delegate;
@synthesize dataPickerView;
@synthesize canInput;
#define HORIZONTALPADDING 10
#define VERTICALPADDING 6
#define WIDTH_BUTTON 73
#define HEIGHT_BUTTON 44

- (UIBarButtonItem*)createCustomBarButton:(NSString*)imageName title:(NSString*)title selector:(SEL)sel{
    UIButton* tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tempButton setExclusiveTouch:YES];
    [tempButton setTitle:title forState:UIControlStateNormal];
    [tempButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    tempButton.frame = CGRectMake(0, 0, 56, 32);
    [tempButton addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* barButton = [[UIBarButtonItem alloc] initWithCustomView:tempButton];
    return [barButton autorelease];
}

- (void)dropClick:(UIButton*)button{
    [[HPUIENG topScreen] hideKeyboard];
    
    if (!self.dataArray || [self.dataArray count] == 0) {
        if (self.noDataTip) {
            [HPUIENG showAlert:self.noDataTip];
        }
        return;
    }
    actionView = [[UIView alloc]initWithFrame:CGRectMake(0, HPUIENG.scrHeight - 216, HPUIENG.scrWidth, HPUIENG.scrHeight)];
    actionView.backgroundColor = [UIColor whiteColor];
//    actionSheet = [[UIActionSheet alloc] init];
//    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
//    [actionSheet setTitle:@"\n\n\n\n\n\n\n\n\n\n\n\n\n"];
    
    UIPickerView* pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, HEIGHT_BUTTON, HPUIENG.scrWidth, 216)];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.showsSelectionIndicator = YES;
    if (self.selectedIndexs) {
        for (int i = 0; i < self.selectedIndexs.count; i ++) {
            int index = [[self.selectedIndexs objectAtIndex:i] intValue];
            if (index < 0) {
                [pickerView selectRow:0 inComponent:i animated:NO];
            }else{
                [pickerView selectRow:index inComponent:i animated:NO];
                [pickerView.delegate pickerView:pickerView didSelectRow:index inComponent:i];
            }
        }
    }
    
    self.dataPickerView = pickerView;
    [pickerView release];
    
    [actionView addSubview:self.dataPickerView];
    
    UIToolbar* accessoryBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, HPUIENG.scrWidth, HEIGHT_BUTTON)];
    [accessoryBar setBarStyle:UIBarStyleBlack];
//    [accessoryBar setTranslucent:YES];
//    [accessoryBar setBackgroundColor:[UIColor clearColor]];
    
    NSMutableArray* buttons = [[NSMutableArray alloc] init];
    UIBarButtonItem* flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    [buttons addObject:[self createCustomBarButton:@"button_cancel.png" title:@"取消" selector:@selector(cancelClick:)]];
    [buttons addObject:flexibleSpace];
    // 将确认按钮背景改成黑色了
    [buttons addObject:[self createCustomBarButton:@"button_cancel.png" title:@"完成" selector:@selector(confirmClick:)]];
    
    [flexibleSpace release];
    
    [accessoryBar setItems:buttons animated:YES];
    [buttons release];
    [actionView addSubview:accessoryBar];
    [accessoryBar release];
    
    
    bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, HPUIENG.scrWidth,HPUIENG.scrHeight)];
    bgView.backgroundColor = RGBACOLOR(0, 0, 0, 0.6);
    
    [bgView addSubview:actionView];
    
    
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];
//    [bgView release];
    
//    [actionSheet showInView:self];
//    [actionSheet release];
}

- (void) confirmClick:(UIButton*)button
{
    BOOL isSame = YES;
    if (self.selectedIndexs.count == self.dataPickerView.numberOfComponents) {
        for (int i = 0; i < self.selectedIndexs.count; i++) {
            NSNumber* index = [self.selectedIndexs objectAtIndex:i];
            if ([index intValue] != [self.dataPickerView selectedRowInComponent:i]) {
                isSame = NO;
                break;
            }
        }
    }else{
        isSame = NO;
    }
    
    if (!isSame) {
        [self.selectedIndexs removeAllObjects];
        for (int i = 0; i < self.dataPickerView.numberOfComponents; i++) {
            [self.selectedIndexs insertObject:@([self.dataPickerView selectedRowInComponent:i]) atIndex:i];
        }
        [self onSure];
    }
    
    self.dataPickerView = nil;
//    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    [bgView removeFromSuperview];
}

- (void) onSure
{
    NSMutableArray *indexs = [NSMutableArray arrayWithCapacity:self.numberOfComponents];
    NSMutableArray *texts = [NSMutableArray arrayWithCapacity:self.numberOfComponents];
    NSString *showText = @"";
    for (int i = 0; i < self.selectedIndexs.count; i ++) {
        NSInteger index = [[self.selectedIndexs objectAtIndex:i] intValue];
        NSArray *datas = [self dataArrayWithComponent:i];
        if (datas && datas.count > index) {
            NSString *text = [datas objectAtIndex:index];
            if (text) {
                showText = [NSString stringWithFormat:@"%@%@", showText, text];
                if (i < self.numberOfComponents - 1) {
                    showText = [NSString stringWithFormat:@"%@ ", showText];
                }
                [indexs addObject:[NSNumber numberWithInteger:index]];
                [texts addObject:text];
            }
        } else {
            [indexs addObject:[NSNumber numberWithInteger:-1]];
        }
    }
    
    contentTextField.text = showText;
    
    if (self.delegate) {
        [self.delegate dropDownListView:self selected:indexs texts:texts];
    }
}

- (void) cancelClick:(UIButton*)button{
//    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    [bgView removeFromSuperview];
}

- (void) setInitContent{
    if (contentTextField.placeholder) {
        [self.selectedIndexs removeAllObjects];
        [self.selectedIndexs insertObject:@(-1) atIndex:0];
        return;
    }
    
    if (!self.dataArray || [self.dataArray count] == 0 || canInput) {
        return;
    }
    
    NSMutableArray *indexs = [NSMutableArray arrayWithCapacity:self.numberOfComponents];
    NSMutableArray *texts = [NSMutableArray arrayWithCapacity:self.numberOfComponents];
    NSString *showText = @"";
    for (int i = 0; i < self.numberOfComponents; i ++) {
        NSInteger index = 0;
        NSArray *datas = [self dataArrayWithComponent:i];
        if (!datas) {
            continue;
        }
        NSString *text = [datas objectAtIndex:index];
        if (!text) {
            continue;
        }
        
        showText = [NSString stringWithFormat:@"%@%@", showText, text];
        if (i < self.numberOfComponents - 1) {
            showText = [NSString stringWithFormat:@"%@ ", showText];
        }
        [indexs addObject:[NSNumber numberWithInteger:index]];
        [texts addObject:text];
    }
    
    contentTextField.text = showText;
    
    if (self.delegate && ![self isHidden]) {
        [self.delegate dropDownListView:self selected:indexs texts:texts];
    }
}

- (void)setPlaceholder:(NSString*)holder{
    contentTextField.placeholder = holder;
    
}

- (NSString*) getText
{
    return contentTextField.text;
}
- (void) setText:(NSString*)text
{
    contentTextField.text = text;
}

- (void) setSelectedIndex:(int)index onComponent:(NSInteger)component
{
    NSArray *dataArray = [self dataArrayWithComponent:component];
    
    if (index >= [dataArray count]) {
        return;
    }
    [self.selectedIndexs insertObject:@(index) atIndex:component];
//    [self.dataPickerView selectRow:index inComponent:component animated:NO];
    
    [self onSure];
}

- (void) setMaxLen:(uint)maxLen
{
    if (contentTextField) {
        [contentTextField setMaxLength:maxLen];
    }
}

- (void) setContentTFtype:(HPConditionType)type{
    if (contentTextField) {
        [contentTextField setConditionType:type];
    }
}

- (void) setContentKebordType:(UIKeyboardType)type{
    if (contentTextField) {
        [contentTextField setKeyboardType:type];
    }
}
- (void) setTextFieldDelegate:(id<UITextFieldDelegate>)textFieldDelegate
{
    contentTextField.delegate = textFieldDelegate;
}

- (void) initializeWithFrame:(CGRect)frame
{
    [self setBackgroundColor:[UIColor clearColor]];
    
    self.realNumberOfComponents = 1;
    
    UIImage *dropImage = [UIImage imageNamed:@"arrowdown.png"];
    
    CGFloat imageRightEdge = (frame.size.width - dropImage.size.width - HORIZONTALPADDING * 2);
    
    dropDownButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
//    [dropDownButton setBackgroundImage:inputBgImage forState:UIControlStateNormal];
    [dropDownButton setImage:dropImage forState:UIControlStateNormal];
    [dropDownButton setImageEdgeInsets:UIEdgeInsetsMake(0, imageRightEdge, 0, 0)];
    [dropDownButton addTarget:self action:@selector(dropClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:dropDownButton];
    
    contentTextField = [[HPConditionTextField alloc] initWithFrame:CGRectMake(HORIZONTALPADDING, 0, imageRightEdge - HORIZONTALPADDING, frame.size.height)];
    contentTextField.userInteractionEnabled = NO;
    contentTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    contentTextField.font = [UIFont systemFontOfSize:16];
    contentTextField.textColor = [UIColor colorWithRed:94./256.f green:94./256.f blue:94./256.f alpha:1.f];
    [self addSubview:contentTextField];
}

- (void)resetView{
    contentTextField.userInteractionEnabled = canInput;
    if (canInput) {
        contentTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        
        UIImage *inputBgImage = [[UIImage imageNamed:@"input_xiala_bg.png"] stretchableImageWithLeftCapWidth:6. topCapHeight:.0];
        UIImageView* imageView = [[UIImageView alloc] initWithImage:inputBgImage];
        imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        [self addSubview:imageView];
        [self sendSubviewToBack:imageView];
        [imageView release];
        
        UIImage *dropImage = [UIImage imageNamed:@"down_tag.png"];
        
        CGFloat imageRightEdge = 38;
        
        //dropDownButton.frame = CGRectMake(self.frame.size.width - (imageRightEdge + dropImage.size.width) / 2, (self.frame.size.height - dropImage.size.height) / 2, dropImage.size.width, dropImage.size.height);
        dropDownButton.frame = CGRectMake(self.frame.size.width - imageRightEdge, 0, imageRightEdge, self.frame.size.height);
        [dropDownButton setImageEdgeInsets:UIEdgeInsetsZero];
        [dropDownButton setImage:dropImage forState:UIControlStateNormal];
        [dropDownButton setBackgroundImage:nil forState:UIControlStateNormal];
        
        contentTextField.frame = CGRectMake(HORIZONTALPADDING, 0, self.frame.size.width - imageRightEdge - HORIZONTALPADDING, self.frame.size.height);
    }else{
        
    }
}

- (void)setCanInput:(BOOL)flag{
    if (canInput == flag) {
        return;
    }
    
    canInput = flag;
    [self resetView];
}

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeWithFrame:frame];
    }
    return self;
}

//- (id)initWithFrame:(CGRect)frame deleagate:(id<HPDropDownListViewDelegate>)dele dataSource:(id<HPDropDownListViewDataSource>)dataSource_
//{
//    self = [super initWithFrame:frame];
//    if (self) {
//        [self initializeWithFrame:frame];
//        self.delegate = dele;
//        self.dataSource = dataSource_;
//    }
//    return self;
//}

- (void) awakeFromNib
{
    [self initializeWithFrame:self.frame];
}

//- (void) setDataSource:(id<HPDropDownListViewDataSource>)dataSource_
//{
//    dataSource = dataSource_;
//    
//    [self reloadData];
//}

- (void)setCurrentText:(NSString *)currentText{
    contentTextField.text = currentText;
}

- (void)setNoDataTipStr:(NSString*)str{
    self.noDataTip = str;
}

- (void) dealloc
{
    self.dataPickerView = nil;
    self.currentText = nil;
    self.noDataTip = nil;
    self.selectedIndexs = nil;
    [dropDownButton release];
    contentTextField.delegate = nil;
    [contentTextField release];
    
    self.delegate = nil;
    self.dataArray = nil;
    
    if (bgView) {
        [bgView release];
        bgView = nil;
    }
    if (actionView) {
        [actionView release];
        actionView = nil;
    }
    [super dealloc];
}

- (void) reloadData
{
//    self.dataArray = [self.dataSource titlesForDropDownListView:self];
    
    for (id data in self.dataArray) {
        int number = [self loadNumberOfComponents:data];
        if (number > self.realNumberOfComponents) {
            self.realNumberOfComponents = number;
        }
    }
    self.selectedIndexs = [NSMutableArray arrayWithCapacity:self.realNumberOfComponents];
    for (int i = 0; i < self.realNumberOfComponents; i ++) {
        [self.selectedIndexs insertObject:@(0) atIndex:i];
    }
    
    if (self.realNumberOfComponents > 1) {
        self.canInput = NO; // 多选不可编辑
    }
    if (!self.canInput) {
        [self setInitContent];
    }
}

- (NSInteger) numberOfComponents
{
    return self.realNumberOfComponents;
}

#pragma mark - 私有方法

- (int) loadNumberOfComponents:(id)data
{
    int ret = 0;
    if ([data isKindOfClass:[NSString class]]) {
        return 1;
    } else if ([data isKindOfClass:[NSArray class]]) {
        NSArray *d0 = (NSArray *)data;
        
        if (d0.count == 2 && [[d0 objectAtIndex:0] isKindOfClass:[NSString class]] && [[d0 objectAtIndex:1] isKindOfClass:[NSArray class]]) {
            ret += 1;
            ret += [self loadNumberOfComponents:[d0 objectAtIndex:1]];
        } else {
            for (id d1 in d0) {
                int number = [self loadNumberOfComponents:d1];
                if (number > ret) {
                    ret = number;
                }
            }
        }
    }
    
    return ret;
}

- (NSArray *) dataArrayWithComponent:(NSInteger)component
{
    NSMutableArray *retArray = [NSMutableArray array];
    if (component == 0) {
        for (id data in self.dataArray) {
            if ([data isKindOfClass:[NSString class]]) {
                [retArray addObject:data];
            } else if ([data isKindOfClass:[NSArray class]] && ((NSArray *)data).count > 0 && [[(NSArray *)data objectAtIndex:0] isKindOfClass:[NSString class]]) {
                [retArray addObject:[(NSArray *)data objectAtIndex:0]];
            }
        }
    } else {
        NSArray *array = self.dataArray;
        for (int i = 0; i <= component; i ++) {
            [retArray removeAllObjects];
            if (i == component) {
                if (array && array.count > 0) {
                    if (array.count == 2 && [[array objectAtIndex:0] isKindOfClass:[NSString class]] && [[array objectAtIndex:1] isKindOfClass:[NSArray class]]) {
                        for (id data in [array objectAtIndex:1]) {
                            if ([data isKindOfClass:[NSString class]]) {
                                [retArray addObject:data];
                            } else if ([data isKindOfClass:[NSArray class]] && ((NSArray *)data).count > 0 && [[(NSArray *)data objectAtIndex:0] isKindOfClass:[NSString class]]) {
                                [retArray addObject:[(NSArray *)data objectAtIndex:0]];
                            }
                        }
                    }
                }
                return retArray;
            }
            NSInteger selectedRow;
            if (self.dataPickerView) {
                selectedRow = [self.dataPickerView selectedRowInComponent:i];
            } else {
                selectedRow = [[self.selectedIndexs objectAtIndex:i] intValue];
            }
            if (i == 0) {
                array = [array objectAtIndex:selectedRow];
            } else {
                if (array && array.count == 2) {
                    array = [[array objectAtIndex:1] objectAtIndex:selectedRow];
                } else {
                    array = nil;
                }
            }
        }
    }
    
    return retArray;
}

- (void)setDropDownImage:(UIImage*)img{
    [dropDownButton setImage:img forState:UIControlStateNormal];
    UIEdgeInsets insets = dropDownButton.imageEdgeInsets;
    insets.top = 3;
    [dropDownButton setImageEdgeInsets:insets];
}

//读取text属性
- (NSString*)readHPtext{
    return contentTextField.text;
}

//设置text属性
- (void)setHPtext:(NSString*)str{
    contentTextField.text = str;
}

- (void)setHPitems:(NSArray*)array{
    self.dataArray = array;
    [self reloadData];
}

- (void)setHPselectedindex:(NSObject *)indexs{
    [self.selectedIndexs removeAllObjects];
    if ([indexs isKindOfClass:[NSNumber class]]) {
        int index = [(NSNumber*)indexs intValue] - 1;
        [self setSelectedIndex:index onComponent:0];
    }else if ([indexs isKindOfClass:[NSArray class]]){
        NSArray* array = (NSArray*)indexs;
        for (int i = 0; i < array.count; i++) {
            int index = [[array objectAtIndex:i] intValue] - 1;
            [self setSelectedIndex:index onComponent:i];
        }
    }
}

- (NSObject *)readHPselectedindex{
    if (self.selectedIndexs.count == 0) {
        return nil;
    }
    if (self.selectedIndexs.count == 1) {
        return @([[self.selectedIndexs objectAtIndex:0] intValue]);
    }
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.realNumberOfComponents];
    for (int i = 0; i < self.selectedIndexs.count; i ++) {
        if ([self dataArrayWithComponent:i].count > 0) {
            [array addObject:@([[self.selectedIndexs objectAtIndex:i] intValue])];
        } else {
            [array addObject:@(-100)];
        }
    }
    
    return array;
}

- (void)setHaveBorder:(BOOL)flag{
    if (flag) {
        UIImage *inputBgImage = [[UIImage imageNamed:@"selecte_bg.png"] stretchableImageWithLeftCapWidth:12. topCapHeight:.0];
        [dropDownButton setBackgroundImage:inputBgImage forState:UIControlStateNormal];
    }else{
        [dropDownButton setBackgroundImage:nil forState:UIControlStateNormal];
    }
}

- (void)setShowFont:(UIFont*)font{
    contentTextField.font = font;
}

- (void)setShowColor:(UIColor *)color{
    contentTextField.textColor = color;
}

- (void)setBgColor:(UIColor *)color{
//    dropDownButton.backgroundColor = color;
//    [HPUtility drawBorderCornerRadius:dropDownButton color:UIColorFromRGB(0xD2D2D2)];
//    [dropDownButton setBackgroundImage:nil forState:UIControlStateNormal];
}

- (void)setTextPosition:(DropDownAlignment)alignment{
    if (alignment == DropDownAlignmentBottom) {
        CGRect rect = contentTextField.frame;
        int v = rect.size.height / 3;
        rect.origin.y = v;
        rect.size.height = rect.size.height - v;
        contentTextField.frame = rect;
        contentTextField.textAlignment = NSTextAlignmentCenter;
    }else if (alignment == DropDownAlignmentRight){
        contentTextField.textAlignment = NSTextAlignmentRight;
    }
}

#pragma mark picker view datasource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return self.realNumberOfComponents;
}

- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [[self dataArrayWithComponent:component] count];
}

#pragma mark - picker view delegate

- (NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [[self dataArrayWithComponent:component] objectAtIndex:row];
}

- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    for (int i = component + 1; i < self.realNumberOfComponents; i ++) {
        [pickerView reloadComponent:i];
    }
}

@end
